<?php
namespace app\index\controller;

use app\common\controller\Base;
use app\ux\UtilFile;

/**
 * 通用文件上传类
 * 作用：文件类型验证，文件大小限制；将相应文件保存到静态文件目录中
 */
class UploadFile extends Base
{

    /**
     * 控制器初始化
     * @return   void
     */
    public function _initialize()
    {
        //基类授权
        //
        parent::_initialize();

    }
    /**
     * 文件上传
     *
     * @param    string $path 上传文件路径
     * @return   void
     */
    public function upload($type, $path)
    {

        try {

            $UtilFile = new UtilFile();

            //目录
            $upload['dir'] = $path;

            // 获取表单上传文件
            $file = request()->file('file');

            // 移到框架静态文件目录/public/static/ 目录下
            if ($file) {

                $path = (ROOT_PATH . 'public' . DS . 'static' . DS . $type . DS . $upload['dir']);

                // 创建目录，默认777
                $UtilFile->mkdirs($path);

                switch ($type) {
                    case 'img':
                        $info = $file->validate(['size' => 2097152, 'ext' => 'jpg,png,gif'])
                            ->move($path, false);
                        break;
                    case 'excel':
                        $info = $file->validate(['size' => 2097152, 'ext' => 'xlsx,xls'])
                            ->move($path, false);
                        break;
                }

                if ($info) {

                    //成功上传后 获取上传信息
                    $fileInfo = $info->getInfo();

                    $upload['ext']      = $info->getExtension();
                    $upload['filename'] = $info->getFilename();
                    $upload['filesize'] = $fileInfo['size'];
                    $upload['path']     = $path . DS . $info->getFilename();

                    if ('img' == $type) {
                        $imgSize          = getimagesize($info->getPathname());
                        $upload['width']  = $imgSize[0];
                        $upload['height'] = $imgSize[1];
                    }

                    $upload['lastmodtime'] = date('Y-m-d H:i:s', filemtime($info->getPathname()));

                    $output['success'] = true;
                    $output['msg']     = '上传成功';
                    $output['data']    = $upload;

                } else {
                    //上传失败获取错误信息
                    $upload['filename'] = '';
                    $upload['filesize'] = 0;
                    $upload['path']     = '';
                    $output['data']     = $upload;
                    $output['success']  = false;
                    $output['msg']      = $file->getError();
                }

                echo json_encode($output);
            }
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * [uploadTag description]
     * @DateTime 2017-11-21
     * @return   [type]
     */
    public function uploadMail()
    {
        $this->upload('excel', 'mail');
    }

}
